import { reactive } from "vue";
import type { FormRules } from "element-plus";

/** 自定义表单规则校验 */
export const formRules = reactive(<FormRules>{
  name: [
    { required: true, message: "时间切片名称为必填项", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "时间切片名称长度应在1-50个字符之间",
      trigger: "blur"
    }
  ],
  startTime: [
    { required: true, message: "开始时间为必填项", trigger: "change" }
  ],
  endTime: [
    {
      required: true,
      message: "结束时间为必填项",
      trigger: "change"
    },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback();
          return;
        }
        // 获取开始时间
        const formEl = ruleFormRef.value;
        if (formEl && formEl.model && formEl.model.startTime) {
          const startTime = new Date(formEl.model.startTime);
          const endTime = new Date(value);
          if (endTime <= startTime) {
            callback(new Error("结束时间必须大于开始时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  lesseeId: [{ required: true, message: "请选择租户", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
});

// 需要导出一个变量来存储表单引用，供规则校验使用
export let ruleFormRef: any;
export function setRuleFormRef(ref: any) {
  ruleFormRef = ref;
}
